package com.wxassistant.controller;

import com.wxassistant.entity.User;
import com.wxassistant.entity.UserCriteria;
import com.wxassistant.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by huangzihao on 2017/12/18.
 */
@Controller
public class HomeController {
    @Autowired
    LoadBalancerClient loadBalancerClient;
    @Autowired
    RestTemplate restTemplate;


    @Autowired
    UserMapper userMapper;

    @RequestMapping({"/","/index"})
    public String index(HttpServletRequest request) {
//        ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-client");
//        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/dc";
//        System.out.println(url);
//        System.out.println(restTemplate.getForObject(url, String.class));
        request.getSession().setAttribute("share-session", "test");
        System.out.println("hello");
        return "index";
    }

    @RequestMapping(value="/login",method= RequestMethod.GET)
    public String login(){
        UserCriteria ue = new UserCriteria();
        ue.setLimit(10);
        ue.setOffset(0);
        List<User> users = userMapper.selectByExample(ue);
        for (int i = 0; i < users.size(); i++) {
            System.out.println(users.get(i).getUsername());
        }
        return"login";
    }

    @RequestMapping("/loginUser")
    public String loginUser(String username,String password,HttpSession session) {
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);   //完成登录
            User user=(User) subject.getPrincipal();
            session.setAttribute("user", user);
            return "index";
        } catch(Exception e) {
            return "login";//返回登录页面
        }

    }
    @RequestMapping("/logOut")
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
//        session.removeAttribute("user");
        return "login";
    }
}
